package com.dangdi.show.util;

import java.io.IOException;
import java.io.StringReader;
import java.util.*;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

public class Xml_MapUtils {
    public static Map<String, Object> xmlToMap(String in) throws DocumentException, IOException {
        StringReader sr = new StringReader(in);
        InputSource is = new InputSource(sr);
        Document doc = new SAXReader().read(is);
        Element root = doc.getRootElement();
        Iterator it = root.elementIterator();
        Map<String, Object> map = new HashMap();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            map.put(e.getName(), e.getText());
        }
        return map;
    }

    public static SortedMap<String, Object> xmlToSortMap(String in) throws DocumentException, IOException {
        StringReader sr = new StringReader(in);
        InputSource is = new InputSource(sr);
        Document doc = new SAXReader().read(is);
        Element root = doc.getRootElement();
        Iterator it = root.elementIterator();
        SortedMap<String, Object> map = new TreeMap<String, Object>();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            map.put(e.getName(), e.getText());
        }
        return map;
    }

    public static String mapToXml(Map map) throws DocumentException, IOException {

        StringBuffer sb = new StringBuffer("");
        sb.append("<xml>");
        Set<String> set = map.keySet();
        for (Iterator<String> it = set.iterator(); it.hasNext(); ) {
            String key = it.next();
            Object value = map.get(key);
            sb.append("<").append(key).append(">");
            sb.append(value);
            sb.append("</").append(key).append(">");
        }
        sb.append("</xml>");
        return sb.toString();

    }

    /**
     * @param parameters 请求参数
     * @return
     * @author
     * @date 2016-4-22
     * @Description：将请求参数转换为xml格式的string
     */
    public static String getRequestXml(SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            } else {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("</xml>");
        System.out.println(sb.toString());
        return sb.toString();
    }

}
